<template>
  <div class="register font-color">
    <div class="register-main">
      <div class="register-main-cont front-color">
        <div class="register_poster">
          <posterBanner></posterBanner>
        </div>
        <div class="register_area">
          <div class="register_area_auto" v-show="regMethodsPage">
            <div class="index-register">
              <div class="register-head clearfix">
                <div class="land" :class='{floatRight: register == "email"}'>
                  <p @click="togTab('tel')" :class='{findactive:register == "tel"}'>{{$t('login.text_01')}}</p>
                </div>
                <div class="land" :class='{floatRight: register == "tel"}'>
                  <p @click="togTab('email')" :class='{findactive:register == "email"}'>{{$t('login.text_02')}}</p>
                </div>
              </div>
            </div>
            <!-- 注册方法页 -->
            <div id="tel-list" class="show">
              <template v-if="countryCodeList.countryCode && this.register === 'tel'">
                <inline-input
                  :property = "countryCodeList.countryCode"
                  v-model="countryCodeList.countryCode.value"
                  v-on:onevents="somethings"
                >
                </inline-input>
              </template>
              <template v-for="(item,key,index) in formList">
                <inline-input
                  :property = "item"
                  v-model = "item.value"
                  @onevents = "somethings">
                </inline-input>
              </template>
              <!-- START阿里云验证 -->
              <template v-if="alYunList.aliyunCapcha">
                <inline-input
                  :property = "alYunList.aliyunCapcha"
                  v-model = "alYunList.aliyunCapcha.value"
                  @onevents = "somethings"
                  @nextActive="nextActive"
                >
                </inline-input>
              </template>
              <!-- END阿里云验证 -->
              <p class="regMethodsPageProm">
                {{$t('login.isAccount')}}
                <router-link to="/login"><i>{{$t('login.login')}}</i></router-link>
              </p>
              <button class="registerBtn registerMethods">{{buttonText}}</button>
            </div>
          </div>
          <!-- 验证码页   -->
          <!-- v-show="verificationPage" -->
          <div class="register_area_auto" v-show="verificationPage">
            <div class="index-register">
              <div class="register-head clearfix">
                <h3>{{$t('login.welcomeRegister')}}</h3>
              </div>
            </div>
            <div id="verify-list">
              <input type="number" class="verifyInput" v-show="register === 'tel'" v-model = "verifyCode" ref="telInput" @input="handleVerifyCode($event.target.value)" :placeholder="$t('myAdd.register.smsVeify')">
              <input type="number" class="verifyInput" v-show="register === 'email'" v-model = "verifyCode" ref="emailInput" @input="handleVerifyCode($event.target.value)"  :placeholder="$t('myAdd.register.emailVerfiy')">
             <!-- <p class="error-info">{{$t('user.api.see_api')}}</p>-->
              <p class="sended" v-show="register === 'tel' && !isSendCode">{{$t('myAdd.register.sendEd')}}: {{formList.mobileNumber && formList.mobileNumber.value}}</p>
              <p class="sended" v-show="register === 'email' && !isSendCode">{{$t('myAdd.register.sendEd')}}{{formList.email && formList.email.value}}</p>
              <p class="verificationPageProm">
                {{$t('login.isAccount')}}
                <router-link to="/login"><i>{{$t('login.login')}}</i></router-link>
              </p>
              <div class="sendCodeDiv">
                <template v-if="alYunList.aliyunCapcha">
                  <inline-input
                    :property = "alYunList.aliyunCapcha"
                    v-model = "alYunList.aliyunCapcha.value"
                    @onevents = "somethings"
                    @nextActive="nextActive"
                  >
                  </inline-input>
                </template>
                <button class="registerBtnCode sendSms" v-show="isSendCode">{{$t('myAdd.register.sendCode')}}</button>
                <button class="registerBtnCode waitSms" v-show="!isSendCode">{{vText}}{{$t('myAdd.register.againSend')}}</button>
              </div>
            </div>
          </div>
          <!-- passworsd页面 -->
        <!--  v-show="passwordPage"-->
          <div class="register_area_auto" v-show="passwordPage">
            <div class="index-register">
              <div class="register-head clearfix">
                <h3>{{$t('login.welcomeRegister')}}</h3>
              </div>
            </div>
            <div class="passlist">
              <template v-for="(item, key, index) in passwordList">
                <inline-input
                  :property = "item"
                  v-model = "item.value"
                  @onevents = "somethings"
                  @textOrPassword="textOrPassword">
                </inline-input>
              </template>
              <span class="robot-check-box">
                <label>
                  <input id="check1" name="check1" type="checkbox" value="true" v-model='checkedNames' checked="checked" class="robot-check" style="">  {{$t('login.text_03')}}
                  <router-link :to="{path:'/cms',query: {id:'terms'}}">{{$t('login.text_04')}} </router-link>
                  <router-link :to="{path:'/cms',query: {id:'privacy_policy'}}">{{$t('login.text_05')}} </router-link>
                  <span class="emptyCycle" v-show="!checkedNames"></span>
                  <span class="checkedCycle"  v-show="checkedNames"></span>
                </label>
                 <p v-if="checkederr" class="error-info" style="">{{$t('login.text_06')}} </p>
              </span>
              <button class="registerPassBtn" :class="{readOnly: !flas}" @click="submit">{{$t('myAdd.register.overReg')}}</button>
              <p class="prom">
                {{$t('login.isAccount')}}
                <router-link to="/login"><i>{{$t('login.login')}}</i></router-link>
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import InlineInput from '@/components/common/inlineInput'
  import { mapState } from 'vuex'
  import posterBanner from './register/posterBanner'
  export default {
    name: 'register',
    components: {
      InlineInput,
      posterBanner
    },
    data () {
      return {
        // 默认显示手机注册
        register: 'tel',
        flas: true,
        formList: {},
        checkedNames: true,
        checkederr: false,
        countryCodeList: {}, // 国家编号
        alYunList: {}, // aliyun验证
        verifyCodeList: {}, // 验证码
        passwordList: {}, // 密码
        regMethodsPage: true, // 注册方法页面显示
        verificationPage: false, // 验证码页面
        passwordPage: false, // 密码页面
        isSendCode: true, // 是否发送验证码
        verifyCode: '', // 输入的验证码
        vText: '',
        timer: null,
        emailReg: /^([a-zA-Z0-9_\\.\-])+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/  // 校验 邮箱
      }
    },
    mounted () {
      this.formList = this.formList_obj
      this.alYunList = this.alYunList_obj
      this.countryCodeList = this.countryCodeList_obj
      this.verifyCodeList = this.verifyCodeList_obj
      this.passwordList = this.passwordList_obj
    },
    watch: {
      'formList_obj' (val) {
        this.formList = val
      },
      'alYunList_obj' (val) {
        this.alYunList = val
      },
      'countryCodeList_obj' (val) {
        this.countryCodeList = val
      },
      'verifyCodeList_obj' (val) {
        this.verifyCodeList = val
      },
      'passwordList_obj' (val) {
        this.passwordList = val
      },
      checkedNames (val) {
        if (val) {
          this.checkederr = false
        } else {
          this.checkederr = true
        }
      }
    },
    computed: {
      ...mapState({
        public_info ({baseData}) {
          if (baseData.isReady) {
            return baseData
          } else {
            return false
          }
        }
      }),
      buttonText () {
        return this.$t('login.nextStep')
      },
      formList_obj () {
        let obj = {}
        if (this.register === 'tel') {
          obj.mobileNumber = {
            title: '',
            subTitle: this.$t('personal.accountNumber'),
            formType: 'phone',
            name: 'mobileNumber',
            value: null,
            placeholder: this.$t('personal.placeholder_16'),
            countryCode: this.$store.state.baseData.default_code
          }
        }
        if (this.register === 'email') {
          obj.email = {
            title: '',
            subTitle: this.$t('personal.accountNumber'),
            formType: 'text',
            placeholder: this.$t('personal.placeholder_15'),
            name: 'email',
            value: null
          }
        }
        // 邀请码
        obj.invitedCode = {
          title: '',
          subTitle: this.$t('personal.placeholder_17'),
          formType: 'text',
          name: 'invitedCode',
          placeholder: this.$t('myAdd.register.enterInviteCode'),
          noRequisite: true,
          value: this.getQueryString('inviteCode')
        }
        return obj
      },
      countryCodeList_obj () { // 国家区号
        return {
          countryCode: {
            title: '',
            subTitle: this.$t('personal.nationality'),
            formType: 'countryCodeRegister',
            name: 'countryCode',
            placeholder: this.$t('personal.placeholder_1'),
            value: this.$store.state.baseData.default_code
          }
        }
      },
      alYunList_obj () { // 阿里云
        return {
          aliyunCapcha: {
            title: '',
            subTitle: this.$t('personal.aliyunCapcha'),
            formType: 'aliyunCapcha',
            alicapcha: {},
            scene: 'register'
          }
        }
      },
      verifyCodeList_obj () { // 验证码
        let obj = {}
        if (this.register === 'tel') {
          obj.smsAuthCode = {
            title: this.$t('personal.smsAuthCode'),
            formType: 'verifiCode',
            name: 'smsAuthCode',
            operationType: 1,
            startTime: false,
            data: ['aliyunCapcha', 'mobileNumber'],
            value: null
          }
        }
        if (this.register === 'email') {
          obj.emailAuthCode = {
            title: this.$t('personal.emailValidCode'),
            formType: 'verifiCode',
            name: 'emailAuthCode',
            operationType: 1,
            startTime: false,
            data: ['aliyunCapcha', 'email'],
            value: null
          }
        }
        return obj
      },
      passwordList_obj () { // 密码
        return {
          loginPword: {
            title: '',
            subTitle: this.$t('login.password'),
            formType: 'password',
            placeholder: this.$t('myAdd.register.password'),
            name: 'loginPword',
            value: null,
            isShowEye: true
          }
        }
      }
    },
    methods: {
      // 获取 URL中的邀请码
      getQueryString (name) {
        let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
        let r = window.location.search.substr(1).match(reg)
        if (r != null) {
          return unescape(r[2])
        }
        return null
      },
      // input 事件
      somethings (value) {
        if (value.handleType === 'sendCode') {
          this.sendCode(value)
        }
      },
      // tab切换
      togTab (res) {
        this.register = res
        this.formList = this.formList_obj
        this.alYunList = this.alYunList_obj
        this.countryCodeList = this.countryCodeList_obj
        this.verifyCodeList = this.verifyCodeList_obj
        this.passwordList = this.passwordList_obj
      },
      // 发送验证码
      sendCode () {
        let item = null
        let data = {}
        let fla = true
        if (this.register === 'tel') {
          item = this.verifyCodeList.smsAuthCode
        }
        if (this.register === 'email') {
          item = this.verifyCodeList.emailAuthCode
        }
        let arr = this.verifyCodeList[item.name].data || []
        if (this.verifyCodeList[item.name].startTime) return false
        if (arr.length > 0) {
          arr.map((item) => {
            if (item === 'aliyunCapcha') {
              if (!this.alYunList[item].alicapcha.token) {
                fla = false
                this.$store.dispatch('setTipState', {text: this.$t('personal.text_6'), type: 'error'})
              }
              data = Object.assign({}, this.alYunList[item].alicapcha, data)
            } else {
              if (!this.formList[item].value) {
                fla = false
                this.$store.dispatch('setTipState', {text: this.$t('personal.text_7') + this.formList[item].subTitle, type: 'error'})
              } else {
                if (this.register === 'tel') {
                  data.countryCode = this.countryCodeList.countryCode.value
                  data.mobile = this.formList[item].value
                } else {
                  data.email = this.formList[item].value
                }
              }
            }
          })
        }
        if (!fla) return false
        data.operationType = this.verifyCodeList[item.name].operationType
        this.verifyCodeList[item.name].startTime = true // 开启倒计时
        data.nc && data.nc.reset() // 重置滑动验证
        data.nc = null
        this.alYunList.aliyunCapcha.alicapcha = {}
        if (this.register === 'tel') {
          this.commonHttp.smsValidCode(data).then((data) => {
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.$t('personal.text_8'))
              // 倒计时
              this.countTime(this.verifyCodeList[item.name])
              this.showEnterVerify()
            } else {
              this.verifyCodeList[item.name].startTime = false // 关闭倒计时
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
          })
        } else if (this.register === 'email') {
          this.commonHttp.emailVaildCode(data).then((data) => {
            if (data.code === '0') {
              this.$store.dispatch('setTipState', this.$t('personal.text_8'))
              this.isSendVerifyCode = true
              // 倒计时
              this.countTime(this.verifyCodeList[item.name])
              this.showEnterVerify()
            } else {
              this.verifyCodeList[item.name].startTime = false // 关闭倒计时
              this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
            }
          })
        }
      },
      // 注册信息提交
      submit () {
        let data = {}
        let url = ''
        let flas = true
        let passwordReg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{8,16}$/
        if (this.register === 'tel') {
          url = this.$store.state.url.register.reg_mobile_h5
          this.formList.mobileNumber.countryCode = this.countryCodeList.countryCode.value
        } else {
          url = this.$store.state.url.register.reg_email_h5
        }
        // 这里把所有的列表数据都合并到一个对象里面
        // this.countryCodeList,
        Object.assign(this.formList, this.alYunList, this.verifyCodeList, this.passwordList)
        for (let item in this.formList) {
          if (this.public_info.invitationCode === '1') {
            if (this.formList[item].value !== undefined && !this.formList[item].value) {
              this.$set(this.formList[item], 'errorInfo', this.$t('personal.text_7') + this.formList[item].subTitle)
              flas = false
            } else {
              data[item] = this.formList[item].value
            }
          } else {
            if (this.formList[item].value !== undefined && !this.formList[item].value && !this.formList[item].noRequisite) {
              this.$set(this.formList[item], 'errorInfo', this.$t('personal.text_7') + this.formList[item].subTitle)
              flas = false
            } else {
              data[item] = this.formList[item].value
            }
          }
        }
        // 判断密码是否正确
        if (data.loginPword && !passwordReg.test(data.loginPword)) {
          this.$set(this.passwordList['loginPword'], 'errorInfo', this.$t('login.text_07'))
          flas = false
        }
        // 如果是手机注册
        if (this.register === 'tel') {
          data.countryCode = this.formList.mobileNumber.countryCode
          // start 胖虎新增验证
          if (data.countryCode === '+86' && !this.formList.mobileNumber.value.startsWith(1)) {
            this.$store.dispatch('setTipState', {text: this.$t('myAdd.register.countryCodeErr'), type: 'error'})
            return false
          }
          // END 胖虎新增验证
        }
        if (!this.checkedNames) {
          this.checkederr = true
          return false
        }
        if (!flas) return false
        if (!this.flas) return false
        this.flas = false
        if (this.register === 'tel') {
          this.formList['smsAuthCode'].value = null
          this.formList['smsAuthCode'].startTime = false
        } else {
          this.formList['emailAuthCode'].value = null
          this.formList['emailAuthCode'].startTime = false
        }
        this.axios({
          url: url,
          headers: {},
          params: data,
          method: 'post'
        }).then((data) => {
          if (data.code.toString() === '0') {
            this.$store.dispatch('setTipState', this.$t('login.registerCuccess'))
            this.$router.push('/login')
          } else {
            this.flas = true
            this.$store.dispatch('setTipState', {text: data.msg, type: 'error'})
          }
        }).catch(() => {
          this.flas = true
        })
      },
      // 阿里云验证成功
      nextActive () {
        if (this.regMethodsPage) {
          for (let item in this.formList) {
            if (this.public_info.invitationCode === '1') {
              if (this.formList[item].value !== undefined && !this.formList[item].value) {
                this.$set(this.formList[item], 'errorInfo', this.$t('personal.text_7') + this.formList[item].subTitle)
                this.alYunList.aliyunCapcha.alicapcha.nc && this.alYunList.aliyunCapcha.alicapcha.nc.reset() // 重置滑动验证
                return false
              }
            } else {
              if (this.formList[item].value !== undefined && !this.formList[item].value && !this.formList[item].noRequisite) {
                this.$set(this.formList[item], 'errorInfo', this.$t('personal.text_7') + this.formList[item].subTitle)
                this.alYunList.aliyunCapcha.alicapcha.nc && this.alYunList.aliyunCapcha.alicapcha.nc.reset()  // 重置滑动验证
                return false
              }
            }
          }
          // this.verifyUser()
          this.sendCode()
        } else if (this.verificationPage) {
          this.sendCode()
          this.alYunList.aliyunCapcha.alicapcha.nc && this.alYunList.aliyunCapcha.alicapcha.nc.reset() // 重置滑动验证
        }
      },
      // 手机号码 或 邮箱号码的后台验证
      verifyUser () {
        let requestData = null
        let userName = null
        let countryCode = null
        let userType = null
        let inviteCode = null
        if (this.register === 'tel') {
          userName = this.formList.mobileNumber.value
          userType = 'mobile'
          countryCode = this.countryCodeList.countryCode.value
        }
        if (this.register === 'email') {
          userType = 'email'
          userName = this.formList.email.value
          let bool = this.emailReg.test(userName)
          if (!bool) {
            this.$store.dispatch('setTipState', {text: this.$t('myAdd.register.emailRegErr'), type: 'error'})
            this.alYunList.aliyunCapcha.alicapcha.nc && this.alYunList.aliyunCapcha.alicapcha.nc.reset()  // 重置滑动验证
            return false
          }
        }
        inviteCode = this.formList.invitedCode.value
        requestData = {userName, countryCode, userType, inviteCode}
        this.axios({
          url: this.$store.state.url.register.verify_user,
          method: 'post',
          params: requestData
        }).then((res) => {
          if (res.code.toString() === '0') {
           /* this.regMethodsPage = true
            this.verificationPage = false
            this.passwordPage = false */
            // 验证成功进入下一步自动送验证码
            this.sendCode()
          } else {
            this.alYunList.aliyunCapcha.alicapcha.nc && this.alYunList.aliyunCapcha.alicapcha.nc.reset()  // 重置滑动验证
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      },
      // 倒计时
      countTime (val) {
        this.isSendCode = false
        let num = 90
        this.vText = num + this.$t('personal.placeholder_11')
        this.timer && clearInterval(this.timer)
        this.timer = setInterval(() => {
          --num
          this.vText = num + this.$t('personal.placeholder_11')
          if (num <= 0) {
            clearInterval(this.timer)
            this.vText = this.$t('personal.getCode')
            val.startTime = false // 关闭倒计时
            this.isSendCode = true
          }
        }, 1000)
      },
      // 输入验证码
      handleVerifyCode (val) {
        if (val.length >= 6) {
          this.$nextTick(() => {
            this.verifyCode = this.verifyCode.substring(0, 6)
          })
        }
        this.verifyCode.length === 6 && this.smsAuthCodeAxios(this.verifyCode)
      },
      // 验证码的校验
      smsAuthCodeAxios (verifyCode) {
        this.register === 'tel' && (this.$refs.telInput.disabled = true)
        this.register === 'email' && (this.$refs.emailInput.disabled = true)
        let userType = null
        let userName = null
        let smsAuthCode = null
        let countryCode = null
        let requestData = null
        if (this.register === 'tel') {
          userName = this.formList.mobileNumber.value
          userType = 'mobile'
          countryCode = this.countryCodeList.countryCode.value
          this.verifyCodeList.smsAuthCode.value = verifyCode // 把验证码的值赋值给verifyCodeList
        }
        if (this.register === 'email') {
          userType = 'email'
          userName = this.formList.email.value
          countryCode = '+86'
          this.verifyCodeList.emailAuthCode.value = verifyCode
        }
        smsAuthCode = verifyCode
        requestData = {userType, userName, smsAuthCode, countryCode}
        this.axios({
          url: this.$store.state.url.register.smsAuthCode,
          method: 'post',
          params: requestData
        }).then((res) => {
          if (res.code.toString() === '0') {
            this.regMethodsPage = false
            this.verificationPage = false
            this.passwordPage = true
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
          this.register === 'tel' && (this.$refs.telInput.disabled = false)
          this.register === 'email' && (this.$refs.emailInput.disabled = false)
        }).catch(() => {
          this.register === 'tel' && (this.$refs.telInput.disabled = false)
          this.register === 'email' && (this.$refs.emailInput.disabled = false)
        })
      },
      // 密码 表单 value 显示隐藏
      textOrPassword () {
        this.passwordList.loginPword.formType = this.passwordList.loginPword.formType === 'password' ? 'text' : 'password'
      },
      // 显示 输入验证码页
      showEnterVerify () {
        this.regMethodsPage = false
        this.verificationPage = true
        this.passwordPage = false
      }
    }
  }
</script>
<style lang='stylus' scoped>
  .bottom{
    border-radius:4px 4px 0 0 !important;
  }
</style>

